import sys, os
sys.path.append(os.pardir)
import numpy as np
from common.functions import *
from deep_learning_demo.common.gradient import numerical_gradient

class TwoLayerNet:

    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
        """
        进行初始化。 
        参数从头开始依次表示
        input_size:  输入层的神经元数
        hidden_size: 隐藏层的神经元数
        output_size: 输出层的神经元数
        """
        self.params = {}
        '''
        保存神经网络的参数的字典型变量（实例变量）。 
        params['W1']是第1层的权重，params['b1']是第1层的偏置。
        params['W2']是第2层的权重，params['b2']是第2层的偏置
        '''
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)

    def predict(self, x):
        """
        进行识别。参数x是图像数据
        """
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']

        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)

        return y

    def loss(self, x, t):

        y = self.predict(x)

        return cross_entropy_error(y, t)


    def accuracy(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1)
        t = np.argmax(t, axis=1)

        accuracy = np.sum(y == t) / float(x.shape[0])
        return accuracy

    def numerical_gradient(self, x, t):
        loss_W = lambda W: self.loss(x, t)
        grads = {} 
        '''
        保存梯度的字典型变量（numerical_gradient()方法的返回值）。 
        grads['W1']是第1层权重的梯度，grads['b1']是第1层偏置的梯度。
        grads['W2']是第2层权重的梯度，grads['b2']是第2层偏置的梯度
        '''
        grads['W1'] = numerical_gradient(loss_W, self.params['W1']) 
        grads['b1'] = numerical_gradient(loss_W, self.params['b1']) 
        grads['W2'] = numerical_gradient(loss_W, self.params['W2']) 
        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
        return grads
    
if __name__ == '__main__':
    net = TwoLayerNet(input_size=784, hidden_size=100, output_size=10)
    x = np.random.rand(100, 784)
    t = np.random.rand(100, 10)
    grads = net.numerical_gradient(x, t)

    print(grads['W1'].shape)
    print(grads['b1'].shape)
    print(grads['W2'].shape)
    print(grads['b2'].shape)
    